/**
 * 路由鉴权
 */
import { getStore } from '@/utils/storage'
import { treeToArray } from '@/utils/tree'

// 路由白名单
const whiteList = ['/login', '/register', '/forget', '/403', '/404'] // no redirect whitelist
// 带有参数的菜单
const haveParamsPath = [
  '/goods/manage/edit',
  '/application/detail',
  '/application/pay',
  '/customer/customer/detail',
  '/customer/vip/detail',
  '/order/manage/detail'
]
export default async ctx => {
  // console.log(ctx)
  const { route, redirect, store } = ctx

  const token = getStore('token')
  let path = route.path
  const haveParamRoute = haveParamsPath.find(ele => {
    return path.indexOf(ele) > -1
  })

  if (haveParamRoute) {
    path = haveParamRoute
  }

  if (whiteList.indexOf(path) > -1) {
    // // 是否是login页面
    // if (path === '/login') {
    //   // 是
    //   if (token) {
    //     // 有 -> 跳往根
    //     redirect({
    //       path: '/'
    //     })
    //   }
    // }
  } else if (!token) {
    redirect({
      path: '/login'
    })
  } else if (token) {
    // const menuPath = '/' + path.split('/')[1]
    // store.commit('menus/SET_CURRENT_MENUS', menuPath)
    // if (store.state.user.userInfo !== getStore('userId')) {
    // }
    // 用户信息
    if (!store.state.user.userInfo || !store.state.menus.appMenus) {
      await store.dispatch('user/getUserInfo', ctx)
      await store.dispatch('menus/getAppMenus', ctx)
    } else if (store.state.user.userInfo.id + '' !== getStore('userId')) {
      await store.dispatch('user/getUserInfo', ctx)
      await store.dispatch('menus/getAppMenus', ctx)
    }

    const appMenus = store.state.menus.appMenus
    if (appMenus && appMenus.length > 0 && path) {
      // debugger
      // path
      const appMenusArr = treeToArray(appMenus)
      // 当前菜单
      const currentMenu = appMenusArr.find(ele => {
        return ele.url === path
      })
      // 当前模块
      let currentModule = {}
      if (currentMenu) {
        currentModule = currentMenu.relation_route[0]
      }
      // 面包屑
      let breadcrumb = []
      if (currentMenu) {
        breadcrumb = currentMenu.relation_route
      }
      // 当前模块
      let defaultSelectedKeys = []
      if (currentMenu) {
        defaultSelectedKeys = [currentMenu.selected_route]
      }
      // 二级菜单
      const subMenusObj = appMenus.find(ele => {
        return ele.url === currentModule.url
      })
      let subMenus = []
      if (subMenusObj) {
        subMenus = subMenusObj.children || []
      }

      store.commit('menus/SET_BREADCRUMB', breadcrumb)
      store.commit('menus/SET_MENU_INFO', {
        defaultSelectedKeys,
        currentModule,
        currentPath: path,
        defaultOpenKeys: breadcrumb.map(ele => ele.url),
        subMenus
      })
    }
  }
}
